<template>
	<view class="container">
		<button @click="requestRecordPermission">请求录音权限</button>
		<button @click="startRecord" :disabled="isRecording || !hasRecordPermission">开始录音</button>
		<button @click="stopRecord" v-if="isRecording || isPaused">停止录音</button>
		<button @click="playAudio" v-if="audioPath">播放录音</button>
		<button @click="stopAudio" v-if="isPlaying">停止播放</button>
		<button @click="getstaticstr" >文字获取</button>
		<view class="container">
		  <view>{{ resultStr }}</view>
		</view>
	</view>
</template>

<script>
	var pdamodule = uni.requireNativePlugin("PDAModule")
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	import IatRecSdk from "../../static/js/iat/iat-rec-sdk";
	import IatFileSdk from "../../static/js/iat/iat-file-sdk";
	export default {
		data() {
			return {
				isRecording: false,
				isPaused: false,
				isPlaying: false,
				audioPath: '',
				hasRecordPermission: false,
				scUrl: "ws://healthai.iflyhealth.com:1028/aimed/v1/saber/iat/ws",
				appId: "MIME1000",
				apiKey: "MIME1000",
				apiSecret: "D9CE5309EADD4BEF91BC03C93578A541",
				resultStr: "",
				isStop: true,
				isUploadFile: false,
				iatRecSdk: null,
				rawFilePath:null
			};
		},
		onLoad() {
			console.log('-------load--------');
			pdamodule.initialize();
			pdamodule.setRecognitionCallback({
			        onRecognitionResult: (result) => {
			            console.log('Received recognition result:', result);
			            this.resultStr = result; // 更新页面上的结果
			        }
			    });
			console.log('-------load--------');
		},
		methods: {
			getstaticstr(){
				let staticstr = pdamodule.getstaticstr()
				this.resultStr = staticstr
				console.log(staticstr)
			},
			requestRecordPermission() {
				const permissions = ['android.permission.RECORD_AUDIO', 'android.permission.WRITE_EXTERNAL_STORAGE'];
				plus.android.requestPermissions(
					permissions,
					(result) => {
						if (result.granted.length === permissions.length) {
							this.hasRecordPermission = true;
							console.log('录音权限授权成功');
						} else {
							uni.showModal({
								title: '提示',
								content: '未获取到录音权限，可能导致应用运行出现问题',
								confirmText: '去开启',
								cancelText: '暂不开启',
								success: (res) => {
									if (res.confirm) {
										plus.runtime.openSystemSetting();
									}
								}
							});
						}
					},
					(error) => {
						console.error('录音权限申请失败:', error.message);
					}
				);
			},
			startRecord() {
				if (this.isRecording) return;
				this.isRecording = true;
				this.isPaused = false;
				recorderManager.start({
					format: 'aac', // 使用aac格式
					sampleRate: 16000,
					bitRate: 96000,
					channels: 1
				});
				
				recorderManager.onStart(() => {
					console.log('录音开始');
				});
			},
			pauseRecord() {
				if (!this.isRecording) return;
				this.isPaused = true;
				recorderManager.pause();
				recorderManager.onPause(() => {
					console.log('录音暂停');
				});
			},
			resumeRecord() {
				if (!this.isPaused) return;
				this.isRecording = true;
				this.isPaused = false;
				recorderManager.resume();
				recorderManager.onResume(() => {
					console.log('录音继续');
				});
			},
			stopRecord() {
				if (!this.isRecording && !this.isPaused) return;
				this.isRecording = false;
				this.isPaused = false;
				recorderManager.stop();
				
				recorderManager.onStop((res) => {
					console.log('录音结束', res.tempFilePath);
					this.audioPath = res.tempFilePath;
					this.performVoiceRecognition();
				});
				if (this.iatRecSdk) {
				    this.iatRecSdk.stop();
				  }
			},
			performVoiceRecognition() {
			            if (pdamodule && this.audioPath) {
			                console.log("========this.audioPath===========" + this.audioPath);
							var finalPath
							var absolutePath
			                // 调用原生模块的 convertAacToRaw 方法
							plus.io.resolveLocalFileSystemURL(this.audioPath, (entry) => {
											            // entry.toLocalURL() 返回的是一个本地路径
											            absolutePath = entry.toLocalURL();
											            console.log("Absolute path: " + absolutePath);
											
											            // 去掉 file:// 前缀
											            finalPath = absolutePath.replace('file://', '');
											            console.log("Final path: " + finalPath);
							
											            
											        }, (e) => {
											            console.error("Error resolving path: " + e.message);
											        });
							
							setTimeout(()=>{
								pdamodule.convertAacToRaw(finalPath, (rawFilePath) => {
								    if (rawFilePath) {
								        console.log("Converted RAW file path:", rawFilePath);
								        this.rawFilePath = rawFilePath;
								        this.startIatFromRawFile();
								    } else {
								        console.error("Failed to convert AAC to RAW");
								    }
								}, (error) => {
								    console.error("Conversion failed:", error);
								});
							},500)
			                
			            }
			        },
			        startIatFromRawFile() {
			            if (pdamodule && this.rawFilePath) {
			                pdamodule.startIatFromFile(this.rawFilePath)
			                    .then(() => {
			                        console.log("Started IAT from RAW file successfully.");
			                    })
			                    .catch((error) => {
			                        console.error("Failed to start IAT from RAW file:", error);
			                    });
			            }
			        },
			playAudio() {
				if (this.isPlaying) return;
				this.isPlaying = true;
				innerAudioContext.src = this.audioPath;
				innerAudioContext.play();
				innerAudioContext.onPlay(() => {
					console.log('播放开始');
				});
				innerAudioContext.onError((err) => {
					console.error('播放错误', err);
				});
			},
			pauseAudio() {
				if (!this.isPlaying) return;
				this.isPlaying = false;
				innerAudioContext.pause();
				innerAudioContext.onPause(() => {
					console.log('播放暂停');
				});
			},
			stopAudio() {
				if (!this.isPlaying) return;
				this.isPlaying = false;
				innerAudioContext.stop();
				innerAudioContext.onStop(() => {
					console.log('播放停止');
				});
			}
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20px;
	}

	button {
		margin: 10px 0;
		padding: 10px 20px;
		font-size: 16px;
	}
</style>